function varargout = FILTERGUI(varargin)
% FILTERGUI MATLAB code for FILTERGUI.fig
%      Created by PEIWEN CONG, SMA, 20.11.10
%      FILTERGUI, by itself, creates a new FILTERGUI or raises the existing
%      singleton*.
%
%      H = FILTERGUI returns the handle to a new FILTERGUI or the handle to
%      the existing singleton*.
%
%      FILTERGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in FILTERGUI.M with the given input arguments.
%
%      FILTERGUI('Property','Value',...) creates a new FILTERGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before FILTERGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to FILTERGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help FILTERGUI

% Last Modified by GUIDE v2.5 25-Feb-2011 12:32:36

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @FILTERGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @FILTERGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before FILTERGUI is made visible.
function FILTERGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to FILTERGUI (see VARARGIN)

% Choose default command line output for FILTERGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% This sets up the initial plot - only do when we are invisible
% so window can get raised using FILTERGUI.
if strcmp(get(hObject,'Visible'),'off')     
    
    % Random seed
    rand('twister', sum(100*clock));
    
    example = 1;
    
    switch example
        case 1
            % Load Example: Random Markov Chain Simulation with normal noise
            % Transition Matrix
            egP = [0.92 0.08; 0.13 0.87];
            % Generate Markov Chain with Stages 0 or 1
            egTruStage = (Markov_Chain(egP,1,200)-1)';
            % Alter time interval
            egTruDyn = kron(egTruStage,ones(50,1));
            % Adding Gaussion Noise
            sigma=1;
            egRawDyn = egTruDyn + (sigma^2).*randn(10000,1);
            % Filter: Moving Average Filter
            span = 100;
            egFilDyn = smooth(egRawDyn, span,'moving');

            set(handles.TD, 'String', ['Ture Dynamics: ' 'Example. Markov Chain Simulation']);
            set(handles.RD, 'String', ['Raw Dynamics: ' 'Example. Gaussion Noise (Sigma = 1)']);
            set(handles.FD, 'String', ['Filter Dynamics: ' 'Example. Moving Average']);
            set(handles.FilMethod,'Value',2);
        case 2
            % Load Example: FFT iFFT Sin Signal with normal noise
            % Initialization
            dt = 1/1000;                                                   % Smapling Rate
            et = 10;                                                       % End of Interval
            t = (0:dt:(et-dt))';                                           % Sampling Range
            egTruDyn = 3*sin(4*2*pi*t) + 5*sin(2*2*pi*t);                  % Signal Model
            sigma=1;
            egRawDyn = egTruDyn + (sigma^2).*randn(10000,1);               % Signal with Noise
            % Fourier Transform
            egRawFFT = fft(egRawDyn);                                      % Fourier Transform
            n = size(egRawDyn,1)/2;                                        % Scaling Size
            egRawFreq = (0:9999)/(2*n*dt);                                 % Freqency
            egRawAmpS = egRawFFT/n;                                        % Amplitude Spectrum
            egRFMax = max(abs(egRawFFT));
            % Filter: FIX MODE
            radius = 0.2;
            egFilFFT = egRawFFT;
            egFilFFT(abs(egRawAmpS)<(egRFMax/n*radius)) = 0;               % Set to Zeros within Radius
            egFiliFFT = ifft(egFilFFT);                                    % inverse Fourier Transform
            egFilDyn = real(egFiliFFT);                                    % Remove Imaginary Parts

            set(handles.TD, 'String', ['Ture Dynamics: ' 'Example. FFT iFFT Sin Signal']);
            set(handles.RD, 'String', ['Raw Dynamics: ' 'Example. Gaussion Noise (Sigma = 1)']);
            set(handles.FD, 'String', ['Filter Dynamics: ' 'Example. FIX MODE (Radius = 0.2)']);
            set(handles.FilMethod,'Value',5);
    end
    
    
    plot(handles.TruDynAxes,egTruDyn);
    axis(handles.TruDynAxes,[1 length(egTruDyn) min(egTruDyn)-.1*abs(max(egTruDyn)-min(egTruDyn)) max(egTruDyn)+.1*abs(max(egTruDyn)-min(egTruDyn))]);
    
    plot(handles.RawDynAxes,egRawDyn);
    axis(handles.RawDynAxes,[1 length(egRawDyn) min(egRawDyn)-.1*abs(max(egRawDyn)-min(egRawDyn)) max(egRawDyn)+.1*abs(max(egRawDyn)-min(egRawDyn))]);
    
    plot(handles.FilDynAxes,egFilDyn);
    axis(handles.FilDynAxes,[1 length(egFilDyn) min(egFilDyn)-.1*abs(max(egFilDyn)-min(egFilDyn)) max(egFilDyn)+.1*abs(max(egFilDyn)-min(egFilDyn))]);
end

% Initrilization

% If the metricdata field is present and the reset flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to reset the data.
if isfield(handles, 'metricdata')
    return;
end

handles.metricdata.TruDyn = egTruDyn;
handles.metricdata.RawDyn = egRawDyn;
handles.metricdata.FilDyn = egFilDyn;

handles.metricdata.TFLAG = 1;
handles.metricdata.RFLAG = 1;
handles.metricdata.FFLAG = 1;

% Update handles structure
guidata(hObject, handles);

% ----------

set(handles.PanelA,'Visible','off');
set(handles.PanelB,'Visible','off');
set(handles.PanelC,'Visible','off');
set(handles.PanelD,'Visible','off');
set(handles.PanelE,'Visible','off');


% UIWAIT makes FILTERGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = FILTERGUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --------------------------------------------------------------------
% LOADING DYNAMICS
% --------------------------------------------------------------------


% --- Executes on button press in LoadTruDyn.
function LoadTruDyn_Callback(hObject, eventdata, handles)
% hObject    handle to LoadTruDyn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% --- Executes on button press in LoadTruDyn.

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

[filename, pathname] = uigetfile('*.dat', 'Pick a Tru Dynamics dat File');
if isequal(filename,0) || isequal(pathname,0)
    % disp('User pressed cancel')
else
    % disp(['User selected ', fullfile(pathname, filename)])
    set(handles.TD, 'String', ['Ture Dynamics: ' pathname filename]);
    
    M = importdata([pathname filename], '\t');
    TruDyn = M.data(:,1);
    
    plot(handles.TruDynAxes,TruDyn);
    axis(handles.TruDynAxes,[1 length(TruDyn) min(TruDyn)-.1*abs(max(TruDyn)-min(TruDyn)) max(TruDyn)+.1*abs(max(TruDyn)-min(TruDyn))]);
    cla(handles.RawDynAxes);
    cla(handles.FilDynAxes);
    set(handles.RD, 'String', 'Raw Dynamics');
    set(handles.FD, 'String', 'Filter Dynamics');
    
    handles.metricdata.TruDyn = TruDyn;
    handles.metricdata.RawDyn = 0;
    handles.metricdata.FilDyn = 0;
    
    handles.metricdata.TFLAG = 1;
    handles.metricdata.RFLAG = 0;
    handles.metricdata.FFLAG = 0;
    
    set(handles.CLTru,'Value',0);
    set(handles.CLRaw,'Value',0);
    
    set(handles.FilMethod,'Value',1);
    
    %SET PARA ON OFF
    set(handles.PanelA,'Visible','off');
    set(handles.PanelB,'Visible','off');
    set(handles.PanelC,'Visible','off');
    set(handles.PanelD,'Visible','off');
    set(handles.PanelE,'Visible','off');

    guidata(hObject, handles);
end

enableButtons(handles);


% --- Executes on button press in LoadRawDyn.
function LoadRawDyn_Callback(hObject, eventdata, handles)
% hObject    handle to LoadRawDyn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

[filename, pathname] = uigetfile('*.dat', 'Pick a Raw Dynamics dat File');
if isequal(filename,0) || isequal(pathname,0)
    % disp('User pressed cancel')
else
    % disp(['User selected ', fullfile(pathname, filename)])
    set(handles.RD, 'String', ['Raw Dynamics: ' pathname filename]);
    
    M = importdata([pathname filename], '\t');
    RawDyn = M.data(:,1);
    
    %disp(length(RawDyn))
    
    plot(handles.RawDynAxes,RawDyn);
    axis(handles.RawDynAxes,[1 length(RawDyn) min(RawDyn)-.1*abs(max(RawDyn)-min(RawDyn)) max(RawDyn)+.1*abs(max(RawDyn)-min(RawDyn))]);
    cla(handles.FilDynAxes);
    set(handles.FD, 'String', 'Filter Dynamics');
    
    handles.metricdata.RawDyn = RawDyn;
    handles.metricdata.FilDyn = 0;
    
    handles.metricdata.RFLAG = 1;
    handles.metricdata.FFLAG = 0;
    
    set(handles.CLTru,'Value',0);
    set(handles.CLRaw,'Value',0);
    
    set(handles.FilMethod,'Value',1);
    
    %SET PARA ON OFF
    set(handles.PanelA,'Visible','off');
    set(handles.PanelB,'Visible','off');
    set(handles.PanelC,'Visible','off');
    set(handles.PanelD,'Visible','off');
    set(handles.PanelE,'Visible','off');
    
    guidata(hObject, handles);
end

enableButtons(handles);


% --------------------------------------------------------------------
% SAVEING DYNAMICS
% --------------------------------------------------------------------


% --- Executes on button press in Save.
function Save_Callback(hObject, eventdata, handles)
% hObject    handle to Save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

[filename, pathname] = uiputfile('*.dat','Save a Fil Dynamics dat File');
if isequal(filename,0) || isequal(pathname,0)
   %disp('User selected Cancel')
else
   %save([pathname filename],handles.metricdata.FilDyn,'-ascii');
    fid = fopen([pathname filename],'w');
    
    fprintf(fid, '%s\t%s %s\n', '#', 'Generated by FILTERGUI *Created by PEIWEN CONG* at', datestr(now)); %title    
    %method and parameters
    FilMethodIndex = get(handles.FilMethod, 'Value');
    switch FilMethodIndex
        case 1 % Blank
            fprintf(fid, '%s\t%s\n', '#', 'Not Processed!');
        case 2 % A.Moving Average
            fprintf(fid, '%s\t%s\n', '#', ['Processed by Moving Average with Span ' get(handles.ASpanE, 'String')]);
        case 3 % B.Modified HMM
            %fprintf(fid, '%s\t%s\n', '#', ['Processed by Modified HMM with Span ' get(handles.ASpanE, 'String')]);            
        case 4 % C.Kalman Smoother
            fprintf(fid, '%s\t%s\n', '#', ['Processed by Kalman Smoother with Process Noise Cov ' get(handles.CProcessE, 'String') ' and Measurement Noise Cov ' get(handles.CMeasureE, 'String')]);
        case 5
        case 6 % E.CK Forward Backward
            %fprintf(fid, '%s\t%s\n', '#', ['Processed by Kalman Smoother with Process Noise Cov ' get(handles.CProcessE, 'String') ' and Measurement Noise Cov ' get(handles.CMeasureE, 'String')]);
    end
    
    fprintf(fid, '%10s\t%10s\n', 'FilDyn','RawDyn'); %colheader
    fprintf(fid, '%10.4f\t%10.4f\n', [handles.metricdata.FilDyn'; handles.metricdata.RawDyn']); %data
    
    fclose(fid);
end

enableButtons(handles);


% --------------------------------------------------------------------
% METHOD POPUP
% --------------------------------------------------------------------


% --- Executes on selection change in FilMethod.
function FilMethod_Callback(hObject, eventdata, handles)
% hObject    handle to FilMethod (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns FilMethod contents as cell array
%        contents{get(hObject,'Value')} returns selected item from FilMethod

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

FilMethodIndex = get(hObject, 'Value');
%set(hObject, 'Value', FilMethodIndex);

switch FilMethodIndex
    case 1 % Blank

        set(handles.PanelA,'Visible','off');
        set(handles.PanelB,'Visible','off');
        set(handles.PanelC,'Visible','off');
        set(handles.PanelD,'Visible','off');
        set(handles.PanelE,'Visible','off');
        
        cla(handles.FilDynAxes);
        set(handles.FD, 'String', 'Filter Dynamics');
        
        handles.metricdata.FilDyn = 0;
        handles.metricdata.FFLAG = 0;
        
    case 2 % Moving Average
        if handles.metricdata.RFLAG
            set(handles.PanelA,'Visible','on');
            set(handles.PanelB,'Visible','off');
            set(handles.PanelC,'Visible','off');
            set(handles.PanelD,'Visible','off');
            set(handles.PanelE,'Visible','off');

            set(handles.FD, 'String', ['Filter Dynamics: Moving Average']);
            
            % Slider Setting
            ASSMin = max(floor(length(handles.metricdata.RawDyn)/1000),5);
            ASSMax = floor(length(handles.metricdata.RawDyn)/10);
            set(handles.ASpanS,'Min',ASSMin); %min span 5
            set(handles.ASpanS,'Max',ASSMax);
            set(handles.ASpanS,'SliderStep',[ASSMin/(ASSMax-ASSMin) ASSMin/(ASSMax-ASSMin)]);

            set(handles.ASpanS,'Value',10*ASSMin);

            set(handles.ASpanE,'String',sprintf('%d', round(get(handles.ASpanS,'Value'))));
            
            % Fitting
            refresh(FILTERGUI);
            FilDyn = smooth(handles.metricdata.RawDyn, round(get(handles.ASpanS,'Value')),'moving');
            % Plotting
            plot(handles.FilDynAxes,FilDyn);
            axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);
            % Updating
            handles.metricdata.FilDyn = FilDyn;
            handles.metricdata.FFLAG = 1;
        end
    case 3 % Modified HMM
        if handles.metricdata.RFLAG
            set(handles.PanelA,'Visible','off');
            set(handles.PanelB,'Visible','on');
            set(handles.PanelC,'Visible','off');
            set(handles.PanelD,'Visible','off');
            set(handles.PanelE,'Visible','off');
            
            set(handles.FD, 'String', ['Filter Dynamics: Modified HMM']);
            
            %Initialization
            %KNN? SVM?
            %Human
            BStatePromp = inputdlg({'States Number'}, 'Modified HMM', 1, {'2'});
            if ~isempty(BStatePromp)
            	BStatePromp = cell2struct(BStatePromp,{'num'});
            	BState = str2num(BStatePromp.num);
        	else
            	BState = 2;
            end
            
            BStateMin = 2;
            BStateMax = 3+BState;
            set(handles.BStateNumS,'Min',BStateMin);
            set(handles.BStateNumS,'Max',BStateMax);
            set(handles.BStateNumS,'SliderStep',[1/(BStateMax-BStateMin) 1/(BStateMax-BStateMin)]);
            
            set(handles.BStateNumS,'Value',BState);
            
            set(handles.BStateNumE,'String',sprintf('%d', round(get(handles.BStateNumS,'Value'))));
            
            %Initialization
            iniTMatrix = ones(BState).*(1/BState);
            iniEPara = [prctile(handles.metricdata.RawDyn,(1:2:2*BState)/(2*BState)*100)' ones(BState,1).*std(handles.metricdata.RawDyn)];
            pFunction = @(x,y)normpdf(x,y(1),y(2));
            
            refresh(FILTERGUI);
            
            TMatrixFix = zeros(BState);
            EParaFix = zeros(BState, 2);         
            [TMatrix, EPara, logLikelihood] = MHMMTRAIN(handles.metricdata.RawDyn, iniTMatrix, iniEPara, TMatrixFix, EParaFix, pFunction);
            
            set(handles.BTMatrixT,'data',TMatrix);
            set(handles.BEParaT,'data',EPara);
            set(handles.BTMatrixFixT,'data',logical(TMatrixFix));
            set(handles.BEParaFixT,'data',logical(EParaFix));
            
            refresh(FILTERGUI);
            [FilDyn, FilDynState] = MHMMVITERBI(handles.metricdata.RawDyn, TMatrix, EPara, pFunction);
            
            % Plotting
            plot(handles.FilDynAxes,FilDyn);
            axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);
            
            plot(handles.BLikelihood,logLikelihood,'b');
            
            % Updating
            handles.metricdata.FilDyn = FilDyn;
            handles.metricdata.FFLAG = 1;
        end
    case 4 % Kalman Smoother
        if handles.metricdata.RFLAG
            set(handles.PanelA,'Visible','off');
            set(handles.PanelB,'Visible','off');
            set(handles.PanelC,'Visible','on');
            set(handles.PanelD,'Visible','off');
            set(handles.PanelE,'Visible','off');

            set(handles.FD, 'String', ['Filter Dynamics: Kalman Smoother']);
            
            % Slider Setting
				% OFF LINE Q R determination
				ASSMin = max(floor(length(handles.metricdata.RawDyn)/1000),5);
				MAFilDyn = smooth(handles.metricdata.RawDyn, 10*ASSMin,'moving');
				
				% Process Noise Cov (Q) Silder
				CPSMax = round(10*var(MAFilDyn));
				CPSMin = CPSMax/100;
				
				set(handles.CProcessS,'Min',CPSMin);
				set(handles.CProcessS,'Max',CPSMax);
				set(handles.CProcessS,'SliderStep',[CPSMin/(CPSMax-CPSMin) CPSMin/(CPSMax-CPSMin)]);
				
				set(handles.CProcessS,'Value',10*CPSMin);
	
				set(handles.CProcessE,'String',sprintf('%.2f', get(handles.CProcessS,'Value')));
				
				% Measurement Noise Cov (R) Silder
				CMSMax = round(10*var(handles.metricdata.RawDyn-MAFilDyn));
				CMSMin = CMSMax/100;
				
				set(handles.CMeasureS,'Min',CMSMin);
				set(handles.CMeasureS,'Max',CMSMax);
				set(handles.CMeasureS,'SliderStep',[CMSMin/(CMSMax-CMSMin) CMSMin/(CMSMax-CMSMin)]);
				
				set(handles.CMeasureS,'Value',10*CMSMin);
	
				set(handles.CMeasureE,'String',sprintf('%.2f', get(handles.CMeasureS,'Value')));
            
            % Initial States
				initX = mean(handles.metricdata.RawDyn);
				initV = 1;
            
            % Fitting
            
            refresh(FILTERGUI);
            [FilDyn, KP] = kalman_smoother(handles.metricdata.RawDyn', 1, 1, get(handles.CProcessS,'Value'), get(handles.CMeasureS,'Value'), initX, initV);
            FilDyn = FilDyn';
            KP = KP(:);
            
            
            % Plotting
            plot(handles.FilDynAxes,FilDyn);
            axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);
            
            plot(handles.KP,KP(1:50));
            axis(handles.KP,[1 length(KP(1:50)) min(KP(1:50))-.1*abs(max(KP(1:50))-min(KP(1:50))) max(KP(1:50))+.1*abs(max(KP(1:50))-min(KP(1:50)))]);
            set(get(handles.KP,'XLabel'),'String','Interation');
            set(get(handles.KP,'YLabel'),'String','Variance^2');
            
            % Updating
            handles.metricdata.FilDyn = FilDyn;
            handles.metricdata.FFLAG = 1;
        end
    case 5 % Fourier Transform
        if handles.metricdata.RFLAG
            set(handles.PanelA,'Visible','off');
            set(handles.PanelB,'Visible','off');
            set(handles.PanelC,'Visible','off');
            set(handles.PanelD,'Visible','on');
            set(handles.PanelE,'Visible','off');
            
            set(handles.FD, 'String', ['Filter Dynamics: Fourier Transform']);
            
            %default mode
            set(handles.DFixPanel,'Visible','on');
            set(handles.DMaskPanel,'Visible','off');
            handles.metricdata.DMFLAG = 0;
            
            % Fourier Transform
            dt = 1/1000; %#########
            RawFFT = fft(handles.metricdata.RawDyn);                       % Fourier Transform
            n = round(size(RawFFT,1)/2);                                   % Scaling Size
            RawFreq = (0:n-1)/(2*n*dt);    % Freqency
            RawAmpS = RawFFT/n;                                            % Amplitude Spectrum            
            
            set(handles.DMASKSize, 'String', ['Variable: MASK        Size: ' sprintf('%d', n)]);
            
            % Updating FFT data
            handles.metricdata.RawFFT = RawFFT;
            handles.metricdata.RawFreq = RawFreq;
            handles.metricdata.RawAmpS = RawAmpS;
            
            % Slider Setting
                ACurrent = 1;
                BCurrent = round(n/50);
                % ZoomA Silder
                DZAMax = BCurrent - 1;
                DZAMin = 1;
                
                set(handles.DZoomAS,'Min',DZAMin);
                set(handles.DZoomAS,'Max',DZAMax);
                set(handles.DZoomAS,'SliderStep',[10/(DZAMax-DZAMin) 10/(DZAMax-DZAMin)]);
                
                set(handles.DZoomAS,'Value',ACurrent);

                set(handles.DZoomAE,'String',sprintf('%d', get(handles.DZoomAS,'Value')));
                % ZoomB Silder
                DZBMax = n;
                DZBMin = ACurrent + 1;
                
                set(handles.DZoomBS,'Min',DZBMin);
                set(handles.DZoomBS,'Max',DZBMax);
                set(handles.DZoomBS,'SliderStep',[10/(DZBMax-DZBMin) 10/(DZBMax-DZBMin)]);
                
                set(handles.DZoomBS,'Value',BCurrent);

                set(handles.DZoomBE,'String',sprintf('%d', get(handles.DZoomBS,'Value')));
            
                % Fix Mode
                % Radius Slider
                DRSMax = 1;
                DRSMin = 0;
                
                set(handles.DRadiusS,'Min',DRSMin);
                set(handles.DRadiusS,'Max',DRSMax);
                set(handles.DRadiusS,'SliderStep',[0.1 0.1]);
                
                set(handles.DRadiusS,'Value',0.2);

                set(handles.DRadiusE,'String',sprintf('%.2f', get(handles.DRadiusS,'Value')));
            
            % Plotting In Panel
                R = real(RawAmpS);
                I = imag(RawAmpS);
                radiusC = max(abs(RawFFT))/n*get(handles.DRadiusS,'Value');
                V = abs(RawAmpS);
                VHalf = V(1:n);
                
                % DSpectrumFIX
                set(handles.DSpectrumFix,'NextPlot','add');            
                circle([0,0],radiusC,1000,'g--',handles.DSpectrumFix);
                plot(handles.DSpectrumFix,RawAmpS(abs(RawAmpS)<radiusC),'bx');
                plot(handles.DSpectrumFix,RawAmpS(abs(RawAmpS)>=radiusC),'r+');
                set(handles.DSpectrumFix,'NextPlot','replace');
                axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);

                % DSpectrumMask
                set(handles.DSpectrumMask,'NextPlot','add');
                if ~(VHalf<radiusC)
                else
                    stem(handles.DSpectrumMask, RawFreq(VHalf<radiusC), VHalf(VHalf<radiusC),'Color','b');
                end
                    stem(handles.DSpectrumMask, RawFreq(VHalf>=radiusC), VHalf(VHalf>=radiusC),'Color','r');
                set(handles.DSpectrumMask,'NextPlot','replace');
                set(handles.DSpectrumMask,'XAxisLocation','top');
                ylim(handles.DSpectrumMask,[min(V)-.1*abs(max(VHalf)-min(VHalf)) max(VHalf)+.1*abs(max(VHalf)-min(VHalf))]);
                xlim(handles.DSpectrumMask,[RawFreq(ACurrent) RawFreq(BCurrent)]);
                xlim(handles.DSpectrumMaskC,[ACurrent BCurrent]);
            
            if handles.metricdata.DMFLAG == 0
                % Filter: FIX MODE
                radius = get(handles.DRadiusS,'Value');
                if radius == 0
                    FilFFT = RawFFT;
                else
                    FilFFT = RawFFT;
                    FilFFT(V<radiusC) = 0;                                 % Set to Zeros within Radius
                end
                FiliFFT = ifft(FilFFT);                                    % inverse Fourier Transform
                FilDyn = real(FiliFFT);                                    % Remove Imaginary Parts
            elseif handles.metricdata.DMFLAG == 1
                % Filter: Mask MODE
            end
            
            % Plotting
            plot(handles.FilDynAxes,FilDyn);
            axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);
            
            
            % Updating
            handles.metricdata.FilDyn = FilDyn;
            handles.metricdata.FFLAG = 1;
        end
    case 6 % CK Forward Backward
        if handles.metricdata.RFLAG
            set(handles.PanelA,'Visible','off');
            set(handles.PanelB,'Visible','off');
            set(handles.PanelC,'Visible','off');
            set(handles.PanelD,'Visible','off');
            set(handles.PanelE,'Visible','on');

            set(handles.FD, 'String', ['Filter Dynamics: CK Forward Backward']);
            
            % Table Setting
            set(handles.EPIC,'Value', 1);
            set(handles.EWC,'Value', 1);
            set(handles.ETable,'ColumnEditable', logical([1 0 1]));
            
            % Slider Setting
                
                % Span
                ESSMin = max(floor(length(handles.metricdata.RawDyn)/1000),5);
                ESSMax = floor(length(handles.metricdata.RawDyn)/100);
                
                set(handles.ESpanS,'Min',ESSMin);
                set(handles.ESpanS,'Max',ESSMax);
                set(handles.ESpanS,'SliderStep',[ESSMin/(ESSMax-ESSMin) ESSMin/(ESSMax-ESSMin)]);
                
                set(handles.ESpanS,'Value',2*ESSMin);

                set(handles.ESpanE,'String',sprintf('%d', round(get(handles.ESpanS,'Value'))));
                
                % Bank Number
                EBSMax = 10;
                EBSMin = 1;
                
                set(handles.EBankS,'Min',EBSMin);
                set(handles.EBankS,'Max',EBSMax);
                set(handles.EBankS,'SliderStep',[EBSMin/(EBSMax-EBSMin) EBSMin/(EBSMax-EBSMin)]);
                
                defaultBANK = 4;
                set(handles.EBankS,'Value',defaultBANK);

                set(handles.EBankE,'String',sprintf('%d', round(get(handles.EBankS,'Value'))));
            
            % Initial Table
            
                BANK = 2.^(1:defaultBANK);
                nbank = defaultBANK*2;
                
                Kfb = sort([BANK -BANK],'descend'); %C1                
                PI = ones(1,nbank)./nbank; %C2
                defaultW = 100; W = ones(1,nbank).*defaultW; %C3
                
                ETableRaw = [Kfb; PI; W]';
                ETableShow = sortrows(ETableRaw(1:defaultBANK,:),1);
                
                set(handles.ETable,'data',ETableShow);
            
            % Fitting

            refresh(FILTERGUI);
            FilDyn = CKFILTER(handles.metricdata.RawDyn', round(get(handles.ESpanS,'Value')), Kfb, W, PI);
            FilDyn = FilDyn';
            
            
            % Plotting
            plot(handles.FilDynAxes,FilDyn);
            axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

            % Updating
            handles.metricdata.FilDyn = FilDyn;
            handles.metricdata.FFLAG = 1;
        end
end

            
set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function FilMethod_CreateFcn(hObject, eventdata, handles)
% hObject    handle to FilMethod (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

set(hObject, 'String', {'Filter Method', 'A. Moving Average', 'B. Modified HMM', 'C. Kalman Smoother','D. Fourier Transform','E. CK Forward Backward'});


% --------------------------------------------------------------------
% A. Moving Average
% --------------------------------------------------------------------


% --- Executes on slider movement.
function ASpanS_Callback(hObject, eventdata, handles)
% hObject    handle to ASpanS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.ASpanE,'String',sprintf('%d', round(get(hObject,'Value'))));

refresh(FILTERGUI);
FilDyn = smooth(handles.metricdata.RawDyn, round(get(hObject,'Value')),'moving');

plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function ASpanS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ASpanS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function ASpanE_Callback(hObject, eventdata, handles)
% hObject    handle to ASpanE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ASpanE as text
%        str2double(get(hObject,'String')) returns contents of ASpanE as a double

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.ASpanS,'Value',str2num(get(hObject,'String')));

refresh(FILTERGUI);
FilDyn = smooth(handles.metricdata.RawDyn, round(get(handles.ASpanS,'Value')),'moving');

plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function ASpanE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ASpanE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
% B. Modified HMM
% --------------------------------------------------------------------

% --- Executes on slider movement.
function BStateNumS_Callback(hObject, eventdata, handles)
% hObject    handle to BStateNumS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

disableButtons(handles);
refresh(FILTERGUI);

set(handles.BStateNumE,'String',sprintf('%d', round(get(hObject,'Value'))));

BState = get(hObject,'Value');
iniTMatrix = ones(BState).*(1/BState);
iniEPara = [prctile(handles.metricdata.RawDyn,(1:2:2*BState)/(2*BState)*100)' ones(BState,1).*std(handles.metricdata.RawDyn)];
pFunction = @(x,y)normpdf(x,y(1),y(2));

refresh(FILTERGUI);

TMatrixFix = zeros(BState);
EParaFix = zeros(BState, 2);           
[TMatrix, EPara, logLikelihood] = MHMMTRAIN(handles.metricdata.RawDyn, iniTMatrix, iniEPara, TMatrixFix, EParaFix, pFunction);

set(handles.BTMatrixT,'data',TMatrix);
set(handles.BEParaT,'data',EPara);
set(handles.BTMatrixFixT,'data',logical(TMatrixFix));
set(handles.BEParaFixT,'data',logical(EParaFix));

refresh(FILTERGUI);
[FilDyn, FilDynState] = MHMMVITERBI(handles.metricdata.RawDyn, TMatrix, EPara, pFunction);

% Plotting
plot(handles.BLikelihood,logLikelihood,'b');
            
plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);

% --- Executes during object creation, after setting all properties.
function BStateNumS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to BStateNumS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function BStateNumE_Callback(hObject, eventdata, handles)
% hObject    handle to BStateNumE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of BStateNumE as text
%        str2double(get(hObject,'String')) returns contents of BStateNumE as a double

disableButtons(handles);
refresh(FILTERGUI);

set(handles.BStateNumS,'Value',str2num(get(hObject,'String')));

BState = get(handles.BStateNumS,'Value');
iniTMatrix = ones(BState).*(1/BState);
iniEPara = [prctile(handles.metricdata.RawDyn,(1:2:2*BState)/(2*BState)*100)' ones(BState,1).*std(handles.metricdata.RawDyn)];
pFunction = @(x,y)normpdf(x,y(1),y(2));

refresh(FILTERGUI);

TMatrixFix = zeros(BState);
EParaFix = zeros(BState, 2);           
[TMatrix, EPara, logLikelihood] = MHMMTRAIN(handles.metricdata.RawDyn, iniTMatrix, iniEPara, TMatrixFix, EParaFix, pFunction);

set(handles.BTMatrixT,'data',TMatrix);
set(handles.BEParaT,'data',EPara);
set(handles.BTMatrixFixT,'data',logical(TMatrixFix));
set(handles.BEParaFixT,'data',logical(EParaFix));

refresh(FILTERGUI);
[FilDyn, FilDynState] = MHMMVITERBI(handles.metricdata.RawDyn, TMatrix, EPara, pFunction);

% Plotting
plot(handles.BLikelihood,logLikelihood,'b');
            
plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);

% --- Executes during object creation, after setting all properties.
function BStateNumE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to BStateNumE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in BDone.
function BDone_Callback(hObject, eventdata, handles)
% hObject    handle to BDone (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

disableButtons(handles);
refresh(FILTERGUI);

pFunction = @(x,y)normpdf(x,y(1),y(2));

TMatrix = get(handles.BTMatrixT,'data');
EPara = get(handles.BEParaT,'data');
TMatrixFix = double(get(handles.BTMatrixFixT,'data'));
EParaFix = double(get(handles.BEParaFixT,'data')); 

[TMatrix, EPara, logLikelihood] = MHMMTRAIN(handles.metricdata.RawDyn, TMatrix, EPara, TMatrixFix, EParaFix, pFunction);

set(handles.BTMatrixT,'data',TMatrix);
set(handles.BEParaT,'data',EPara);

refresh(FILTERGUI);
[FilDyn, FilDynState] = MHMMVITERBI(handles.metricdata.RawDyn, TMatrix, EPara, pFunction);

% Plotting
plot(handles.BLikelihood,logLikelihood,'b');
            
plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);



% --------------------------------------------------------------------
% C. Kalman Smoother
% --------------------------------------------------------------------


% --- Executes on slider movement.
function CProcessS_Callback(hObject, eventdata, handles)
% hObject    handle to CProcessS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.CProcessE,'String',sprintf('%.2f', get(hObject,'Value')));

% Initial States
initX = mean(handles.metricdata.RawDyn);
initV = 1;

refresh(FILTERGUI);
[FilDyn, KP] = kalman_smoother(handles.metricdata.RawDyn', 1, 1, get(hObject,'Value'), get(handles.CMeasureS,'Value'), initX, initV);
FilDyn = FilDyn';
KP = KP(:);


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

plot(handles.KP,KP(1:50));
axis(handles.KP,[1 length(KP(1:50)) min(KP(1:50))-.1*abs(max(KP(1:50))-min(KP(1:50))) max(KP(1:50))+.1*abs(max(KP(1:50))-min(KP(1:50)))]);
set(get(handles.KP,'XLabel'),'String','Interation');
set(get(handles.KP,'YLabel'),'String','Variance^2');

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function CProcessS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CProcessS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function CProcessE_Callback(hObject, eventdata, handles)
% hObject    handle to CProcessE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of CProcessE as text
%        str2double(get(hObject,'String')) returns contents of CProcessE as a double

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.CProcessS,'Value',str2num(get(hObject,'String')));

% Initial States
initX = mean(handles.metricdata.RawDyn);
initV = 1;

refresh(FILTERGUI);
[FilDyn, KP] = kalman_smoother(handles.metricdata.RawDyn', 1, 1, get(handles.CProcessS,'Value'), get(handles.CMeasureS,'Value'), initX, initV);
FilDyn = FilDyn';
KP = KP(:);


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

plot(handles.KP,KP(1:50));
axis(handles.KP,[1 length(KP(1:50)) min(KP(1:50))-.1*abs(max(KP(1:50))-min(KP(1:50))) max(KP(1:50))+.1*abs(max(KP(1:50))-min(KP(1:50)))]);
set(get(handles.KP,'XLabel'),'String','Interation');
set(get(handles.KP,'YLabel'),'String','Variance^2'); 

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);

% --- Executes during object creation, after setting all properties.
function CProcessE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CProcessE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on slider movement.
function CMeasureS_Callback(hObject, eventdata, handles)
% hObject    handle to CMeasureS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.CMeasureE,'String',sprintf('%.2f', get(hObject,'Value')));

% Initial States
initX = mean(handles.metricdata.RawDyn);
initV = 1;

refresh(FILTERGUI);
[FilDyn, KP] = kalman_smoother(handles.metricdata.RawDyn', 1, 1, get(handles.CProcessS,'Value'), get(hObject,'Value'), initX, initV);
FilDyn = FilDyn';
KP = KP(:);


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

plot(handles.KP,KP(1:50));
axis(handles.KP,[1 length(KP(1:50)) min(KP(1:50))-.1*abs(max(KP(1:50))-min(KP(1:50))) max(KP(1:50))+.1*abs(max(KP(1:50))-min(KP(1:50)))]);
set(get(handles.KP,'XLabel'),'String','Interation');
set(get(handles.KP,'YLabel'),'String','Variance^2');

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function CMeasureS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CMeasureS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function CMeasureE_Callback(hObject, eventdata, handles)
% hObject    handle to CMeasureE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of CMeasureE as text
%        str2double(get(hObject,'String')) returns contents of CMeasureE as a double

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.CMeasureS,'Value',str2num(get(hObject,'String')));

% Initial States
initX = mean(handles.metricdata.RawDyn);
initV = 1;

refresh(FILTERGUI);
[FilDyn, KP] = kalman_smoother(handles.metricdata.RawDyn', 1, 1, get(handles.CProcessS,'Value'), get(handles.CMeasureS,'Value'), initX, initV);
FilDyn = FilDyn';
KP = KP(:);

plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

plot(handles.KP,KP(1:50));
axis(handles.KP,[1 length(KP(1:50)) min(KP(1:50))-.1*abs(max(KP(1:50))-min(KP(1:50))) max(KP(1:50))+.1*abs(max(KP(1:50))-min(KP(1:50)))]);
set(get(handles.KP,'XLabel'),'String','Interation');
set(get(handles.KP,'YLabel'),'String','Variance^2');

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function CMeasureE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CMeasureE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
% D. Fourier Transform
% --------------------------------------------------------------------


% --- Executes on slider movement.
function DRadiusS_Callback(hObject, eventdata, handles)
% hObject    handle to DRadiusS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.DRadiusE,'String',sprintf('%.2f', get(hObject,'Value')));

% Updating FFT data
RawFFT = handles.metricdata.RawFFT;
RawFreq = handles.metricdata.RawFreq;
RawAmpS = handles.metricdata.RawAmpS;

n = round(size(RawFFT,1)/2);

% Plotting In Panel
R = real(RawAmpS);
I = imag(RawAmpS);
radiusC = max(abs(RawFFT))/n*get(handles.DRadiusS,'Value');
V = abs(RawAmpS);
VHalf = V(1:n);

cla(handles.DSpectrumFix);
set(handles.DSpectrumFix,'NextPlot','add');            
circle([0,0],radiusC,1000,'g--',handles.DSpectrumFix);
plot(handles.DSpectrumFix,RawAmpS(V<radiusC),'bx');
plot(handles.DSpectrumFix,RawAmpS(V>=radiusC),'r+');
set(handles.DSpectrumFix,'NextPlot','replace');
axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);

if get(handles.DSquare,'Value')
    axis(handles.DSpectrumFix,[min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
else
    axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
end


cla(handles.DSpectrumMask);
set(handles.DSpectrumMask,'NextPlot','add');
if ~(VHalf<radiusC)
else
    stem(handles.DSpectrumMask, RawFreq(VHalf<radiusC), VHalf(VHalf<radiusC),'Color','b');
end
    stem(handles.DSpectrumMask, RawFreq(VHalf>=radiusC), VHalf(VHalf>=radiusC),'Color','r');
set(handles.DSpectrumMask,'NextPlot','replace');
set(handles.DSpectrumMask,'XAxisLocation','top');
ylim(handles.DSpectrumMask,[min(VHalf)-.1*abs(max(VHalf)-min(VHalf)) max(VHalf)+.1*abs(max(VHalf)-min(VHalf))]);
xlim(handles.DSpectrumMask,[RawFreq(get(handles.DZoomAS,'Value')),RawFreq(get(handles.DZoomBS,'Value'))]);
xlim(handles.DSpectrumMaskC,[get(handles.DZoomAS,'Value') get(handles.DZoomBS,'Value')]);

refresh(FILTERGUI);

if handles.metricdata.DMFLAG == 0
    % Filter: FIX MODE
    radius = get(handles.DRadiusS,'Value');
    if radius == 0
        FilFFT = RawFFT;
    else
        %FilFFT = fix(RawFFT/(n*radiusC))*(n*radiusC); 
        FilFFT = RawFFT;
        FilFFT(V<radiusC) = 0;                                             % Set to Zeros within Radius
    end
    FiliFFT = ifft(FilFFT);                                                % inverse Fourier Transform
    FilDyn = real(FiliFFT);                                                % Remove Imaginary Parts
elseif handles.metricdata.DMFLAG == 1
    % Filter: Mask MODE
end

plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function DRadiusS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DRadiusS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function DRadiusE_Callback(hObject, eventdata, handles)
% hObject    handle to DRadiusE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of DRadiusE as text
%        str2double(get(hObject,'String')) returns contents of DRadiusE as a double

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.DRadiusS,'Value',str2double(get(hObject,'String')));

% Updating FFT data
RawFFT = handles.metricdata.RawFFT;
RawFreq = handles.metricdata.RawFreq;
RawAmpS = handles.metricdata.RawAmpS;

n = round(size(RawFFT,1)/2);

% Plotting In Panel
R = real(RawAmpS);
I = imag(RawAmpS);
radiusC = max(abs(RawFFT))/n*get(handles.DRadiusS,'Value');
V = abs(RawAmpS);
VHalf = V(1:n);

cla(handles.DSpectrumFix);
set(handles.DSpectrumFix,'NextPlot','add');            
circle([0,0],radiusC,1000,'g--',handles.DSpectrumFix);
plot(handles.DSpectrumFix,RawAmpS(abs(RawAmpS)<radiusC),'bx');
plot(handles.DSpectrumFix,RawAmpS(abs(RawAmpS)>=radiusC),'r+');
set(handles.DSpectrumFix,'NextPlot','replace');

axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);

if get(handles.DSquare,'Value')
    axis(handles.DSpectrumFix,[min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
else
    axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
end


cla(handles.DSpectrumMask);
set(handles.DSpectrumMask,'NextPlot','add');
if ~(VHalf<radiusC)
else
    stem(handles.DSpectrumMask, RawFreq(VHalf<radiusC), VHalf(VHalf<radiusC),'Color','b');
end
    stem(handles.DSpectrumMask, RawFreq(VHalf>=radiusC), VHalf(VHalf>=radiusC),'Color','r');
set(handles.DSpectrumMask,'NextPlot','replace');
set(handles.DSpectrumMask,'XAxisLocation','top');
ylim(handles.DSpectrumMask,[min(VHalf)-.1*abs(max(VHalf)-min(VHalf)) max(VHalf)+.1*abs(max(VHalf)-min(VHalf))]);
xlim(handles.DSpectrumMask,[RawFreq(get(handles.DZoomAS,'Value')),RawFreq(get(handles.DZoomBS,'Value'))]);
xlim(handles.DSpectrumMaskC,[get(handles.DZoomAS,'Value') get(handles.DZoomBS,'Value')]);

refresh(FILTERGUI);

if handles.metricdata.DMFLAG == 0
    % Filter: FIX MODE
    radius = get(handles.DRadiusS,'Value');
    if radius == 0
        FilFFT = RawFFT;
    else
        FilFFT = RawFFT;
        FilFFT(V<radiusC) = 0;                                             % Set to Zeros within Radius
    end
    FiliFFT = ifft(FilFFT);                                                % inverse Fourier Transform
    FilDyn = real(FiliFFT);                                                % Remove Imaginary Parts
elseif handles.metricdata.DMFLAG == 1
    % Filter: Mask MODE
end

plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function DRadiusE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DRadiusE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on slider movement.
function DZoomAS_Callback(hObject, eventdata, handles)
% hObject    handle to DZoomAS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

ACurrent = round(get(hObject,'Value'));
BCurrent = get(handles.DZoomBS,'Value');

set(hObject,'Value', ACurrent);
set(handles.DZoomAE,'String',sprintf('%d', ACurrent));
set(handles.DZoomBS,'Min', ACurrent + 1);

DZAMax = get(hObject,'Max');
DZAMin = get(hObject,'Min');
DZBMax = get(handles.DZoomBS,'Max');
DZBMin = get(handles.DZoomBS,'Min');

if DZAMax - DZAMin < 10
    DZAStep = 1/(DZAMax-DZAMin);
else
    DZAStep = 10/(DZAMax-DZAMin);
end
if DZBMax - DZBMin < 10
    DZBStep = 1/(DZBMax-DZBMin);
else
    DZBStep = 10/(DZBMax-DZBMin);
end
set(handles.DZoomAS,'SliderStep',[DZAStep DZAStep]);
set(handles.DZoomBS,'SliderStep',[DZBStep DZBStep]);

RawFreq = handles.metricdata.RawFreq;
xlim(handles.DSpectrumMask,[RawFreq(ACurrent) RawFreq(BCurrent)]);
xlim(handles.DSpectrumMaskC,[ACurrent BCurrent]);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function DZoomAS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DZoomAS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function DZoomAE_Callback(hObject, eventdata, handles)
% hObject    handle to DZoomAE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of DZoomAE as text
%        str2double(get(hObject,'String')) returns contents of DZoomAE as a double
disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

ACurrent = str2num(get(hObject,'String'));
BCurrent = get(handles.DZoomBS,'Value');

if ACurrent >= BCurrent
    ACurrent = BCurrent - 1;
    set(hObject,'String',sprintf('%d', ACurrent));
end

DZAMax = max(get(handles.DZoomAS,'Max'), ACurrent);
DZAMin = get(handles.DZoomAS,'Min');
set(handles.DZoomAS,'Max',DZAMax);
set(handles.DZoomAS,'Value', ACurrent);
set(handles.DZoomBS,'Min', ACurrent + 1);

DZBMax = get(handles.DZoomBS,'Max');
DZBMin = get(handles.DZoomBS,'Min');

if DZAMax - DZAMin < 10
    DZAStep = 1/(DZAMax-DZAMin);
else
    DZAStep = 10/(DZAMax-DZAMin);
end
if DZBMax - DZBMin < 10
    DZBStep = 1/(DZBMax-DZBMin);
else
    DZBStep = 10/(DZBMax-DZBMin);
end
set(handles.DZoomAS,'SliderStep',[DZAStep DZAStep]);
set(handles.DZoomBS,'SliderStep',[DZBStep DZBStep]);

RawFreq = handles.metricdata.RawFreq;
xlim(handles.DSpectrumMask,[RawFreq(ACurrent) RawFreq(BCurrent)]);
xlim(handles.DSpectrumMaskC,[ACurrent BCurrent]);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function DZoomAE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DZoomAE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on slider movement.
function DZoomBS_Callback(hObject, eventdata, handles)
% hObject    handle to DZoomBS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

ACurrent = get(handles.DZoomAS,'Value');
BCurrent = round(get(hObject,'Value'));

set(hObject,'Value', BCurrent);
set(handles.DZoomBE,'String',sprintf('%d', BCurrent));
set(handles.DZoomAS,'Max', BCurrent - 1);

DZBMax = get(hObject,'Max');
DZBMin = get(hObject,'Min');
DZAMax = get(handles.DZoomAS,'Max');
DZAMin = get(handles.DZoomAS,'Min');

if DZAMax - DZAMin < 10
    DZAStep = 1/(DZAMax-DZAMin);
else
    DZAStep = 10/(DZAMax-DZAMin);
end
if DZBMax - DZBMin < 10
    DZBStep = 1/(DZBMax-DZBMin);
else
    DZBStep = 10/(DZBMax-DZBMin);
end
set(handles.DZoomAS,'SliderStep',[DZAStep DZAStep]);
set(handles.DZoomBS,'SliderStep',[DZBStep DZBStep]);

RawFreq = handles.metricdata.RawFreq;
xlim(handles.DSpectrumMask,[RawFreq(ACurrent) RawFreq(BCurrent)]);
xlim(handles.DSpectrumMaskC,[ACurrent BCurrent]);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function DZoomBS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DZoomBS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function DZoomBE_Callback(hObject, eventdata, handles)
% hObject    handle to DZoomBE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of DZoomBE as text
%        str2double(get(hObject,'String')) returns contents of DZoomBE as a double
disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

ACurrent = get(handles.DZoomAS,'Value');
BCurrent = str2num(get(hObject,'String'));

if BCurrent <= ACurrent
    BCurrent = ACurrent + 1;
    set(hObject,'String',sprintf('%d', BCurrent));
end

DZBMax = get(handles.DZoomBS,'Max');
DZBMin = min(get(handles.DZoomBS,'Min'), BCurrent);
set(handles.DZoomBS,'Min',DZBMin);
set(handles.DZoomBS,'Value', BCurrent);
set(handles.DZoomAS,'Max', BCurrent - 1);

DZAMax = get(handles.DZoomAS,'Max');
DZAMin = get(handles.DZoomAS,'Min');

if DZAMax - DZAMin < 10
    DZAStep = 1/(DZAMax-DZAMin);
else
    DZAStep = 10/(DZAMax-DZAMin);
end
if DZBMax - DZBMin < 10
    DZBStep = 1/(DZBMax-DZBMin);
else
    DZBStep = 10/(DZBMax-DZBMin);
end
set(handles.DZoomAS,'SliderStep',[DZAStep DZAStep]);
set(handles.DZoomBS,'SliderStep',[DZBStep DZBStep]);

RawFreq = handles.metricdata.RawFreq;
xlim(handles.DSpectrumMask,[RawFreq(ACurrent) RawFreq(BCurrent)]);
xlim(handles.DSpectrumMaskC,[ACurrent BCurrent]);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function DZoomBE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DZoomBE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in DSquare.
function DSquare_Callback(hObject, eventdata, handles)
% hObject    handle to DSquare (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DSquare

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

RawAmpS = handles.metricdata.RawAmpS;

R = real(RawAmpS);
I = imag(RawAmpS);

if get(hObject,'Value')
    axis(handles.DSpectrumFix,[min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
else
    axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
end

enableButtons(handles);


% --- Executes on button press in DFSwitch.
function DFSwitch_Callback(hObject, eventdata, handles)
% hObject    handle to DFSwitch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DFSwitch
disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

if get(hObject,'Value')
    set(handles.DFixPanel,'Visible','off');
    set(handles.DMaskPanel,'Visible','on');
    handles.metricdata.DMFLAG = 1;
    set(hObject,'Value',0);
    
    % Updating FFT data
    RawFFT = handles.metricdata.RawFFT;
    RawFreq = handles.metricdata.RawFreq;
    RawAmpS = handles.metricdata.RawAmpS;

    n = round(size(RawFFT,1)/2);

    % Plotting In Panel
    R = real(RawAmpS);
    I = imag(RawAmpS);
    V = abs(RawAmpS);
    VHalf = V(1:n);

    cla(handles.DSpectrumFix);
    plot(handles.DSpectrumFix,RawAmpS,'bx');

    axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);

    if get(handles.DSquare,'Value')
        axis(handles.DSpectrumFix,[min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
    else
        axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
    end


    cla(handles.DSpectrumMask);
    stem(handles.DSpectrumMask, RawFreq, VHalf,'Color','b');
    set(handles.DSpectrumMask,'XAxisLocation','top');
    ylim(handles.DSpectrumMask,[min(VHalf)-.1*abs(max(VHalf)-min(VHalf)) max(VHalf)+.1*abs(max(VHalf)-min(VHalf))]);
    xlim(handles.DSpectrumMask,[RawFreq(get(handles.DZoomAS,'Value')),RawFreq(get(handles.DZoomBS,'Value'))]);
    xlim(handles.DSpectrumMaskC,[get(handles.DZoomAS,'Value') get(handles.DZoomBS,'Value')]);
    
    refresh(FILTERGUI);
    
    if handles.metricdata.DMFLAG == 0
        % Filter: FIX MODE
    elseif handles.metricdata.DMFLAG == 1
        % Filter: Mask MODE
        FilFFT = RawFFT;
        FiliFFT = ifft(FilFFT);
        FilDyn = real(FiliFFT);
    end

    plot(handles.FilDynAxes,FilDyn);
    axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

    handles.metricdata.FilDyn = FilDyn;

    set(handles.CLTru,'Value',0);
    set(handles.CLRaw,'Value',0);
    
    guidata(hObject, handles);
end

enableButtons(handles);


% --- Executes on button press in DMSwitch.
function DMSwitch_Callback(hObject, eventdata, handles)
% hObject    handle to DMSwitch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DMSwitch
disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

if get(hObject,'Value')
    set(handles.DFixPanel,'Visible','on');
    set(handles.DMaskPanel,'Visible','off');
    handles.metricdata.DMFLAG = 0;
    set(hObject,'Value',0);
    
    % Updating FFT data
    RawFFT = handles.metricdata.RawFFT;
    RawFreq = handles.metricdata.RawFreq;
    RawAmpS = handles.metricdata.RawAmpS;

    n = round(size(RawFFT,1)/2);

    % Plotting In Panel
    R = real(RawAmpS);
    I = imag(RawAmpS);
    radiusC = max(abs(RawFFT))/n*get(handles.DRadiusS,'Value');
    V = abs(RawAmpS);
    VHalf = V(1:n);

    cla(handles.DSpectrumFix);
    set(handles.DSpectrumFix,'NextPlot','add');            
    circle([0,0],radiusC,1000,'g--',handles.DSpectrumFix);
    plot(handles.DSpectrumFix,RawAmpS(abs(RawAmpS)<radiusC),'bx');
    plot(handles.DSpectrumFix,RawAmpS(abs(RawAmpS)>=radiusC),'r+');
    set(handles.DSpectrumFix,'NextPlot','replace');

    axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);

    if get(handles.DSquare,'Value')
        axis(handles.DSpectrumFix,[min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
    else
        axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
    end


    cla(handles.DSpectrumMask);
    set(handles.DSpectrumMask,'NextPlot','add');
    stem(handles.DSpectrumMask, RawFreq(VHalf<radiusC), VHalf(VHalf<radiusC),'Color','b');
    stem(handles.DSpectrumMask, RawFreq(VHalf>=radiusC), VHalf(VHalf>=radiusC),'Color','r');
    set(handles.DSpectrumMask,'NextPlot','replace');
    set(handles.DSpectrumMask,'XAxisLocation','top');
    ylim(handles.DSpectrumMask,[min(VHalf)-.1*abs(max(VHalf)-min(VHalf)) max(VHalf)+.1*abs(max(VHalf)-min(VHalf))]);
    xlim(handles.DSpectrumMask,[RawFreq(get(handles.DZoomAS,'Value')),RawFreq(get(handles.DZoomBS,'Value'))]);
    xlim(handles.DSpectrumMaskC,[get(handles.DZoomAS,'Value') get(handles.DZoomBS,'Value')]);
    
    refresh(FILTERGUI);

    if handles.metricdata.DMFLAG == 0
        % Filter: FIX MODE
        radius = get(handles.DRadiusS,'Value');
        if radius == 0
            FilFFT = RawFFT;
        else
            FilFFT = RawFFT;
            FilFFT(V<radiusC) = 0;                                             % Set to Zeros within Radius
        end
        FiliFFT = ifft(FilFFT);                                                % inverse Fourier Transform
        FilDyn = real(FiliFFT);                                                % Remove Imaginary Parts
    elseif handles.metricdata.DMFLAG == 1
        % Filter: Mask MODE
    end

    plot(handles.FilDynAxes,FilDyn);
    axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

    handles.metricdata.FilDyn = FilDyn;

    set(handles.CLTru,'Value',0);
    set(handles.CLRaw,'Value',0);

    guidata(hObject, handles);
end

enableButtons(handles);


function DCommandE_Callback(hObject, eventdata, handles)
% hObject    handle to DCommandE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of DCommandE as text
%        str2double(get(hObject,'String')) returns contents of DCommandE as a double

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

RawFFT = handles.metricdata.RawFFT;
RawFreq = handles.metricdata.RawFreq;
RawAmpS = handles.metricdata.RawAmpS;

dt = 1/1000; %######
n = round(size(RawFFT,1)/2);

eval(get(hObject,'String')); % MASK vertical vector

% full size MASK
if rem(n,2) == 1 % odd
    MASKF = [MASK; flipud(MASK(2:length(MASK)))];
else % even
    MASKF = [MASK; flipud(MASK)];
end

if length(RawFFT) == length(MASKF)
    
    if MASKF == 0 | MASKF == 1 % Square
        MASKS = kron(MASK,ones(100,1));
        FreqS = (0-50:100*n-1-50)/(2*100*n*dt); % with correction
    else
        MASKS = interp(MASK,100); %Gradual
        FreqS = (0:100*n-1)/(2*100*n*dt);
    end
    
    % Plotting In Panel
    R = real(RawAmpS);
    I = imag(RawAmpS);
    V = abs(RawAmpS);
    VHalf = V(1:n);

    cla(handles.DSpectrumFix);
    set(handles.DSpectrumFix,'NextPlot','add');            
    plot(handles.DSpectrumFix,RawAmpS(MASKF<0.5),'bx');
    plot(handles.DSpectrumFix,RawAmpS(MASKF>=.5),'r+');
    set(handles.DSpectrumFix,'NextPlot','replace');

    axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);

    if get(handles.DSquare,'Value')
        axis(handles.DSpectrumFix,[min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
    else
        axis(handles.DSpectrumFix,[min(R)-.1*abs(max(R)-min(R)) max(R)+.1*abs(max(R)-min(R)) min(I)-.1*abs(max(I)-min(I)) max(I)+.1*abs(max(I)-min(I))]);
    end


    cla(handles.DSpectrumMask);
    set(handles.DSpectrumMask,'NextPlot','add');
    if ~(VHalf<0.5)
    else
        stem(handles.DSpectrumMask, RawFreq(MASK<0.5), VHalf(MASK<0.5),'Color','b');
    end
        stem(handles.DSpectrumMask, RawFreq(MASK>=.5), VHalf(MASK>=.5),'Color','r');
    plot(handles.DSpectrumMask, FreqS, MASKS.*max(VHalf),'g-.');
    set(handles.DSpectrumMask,'NextPlot','replace');
    set(handles.DSpectrumMask,'XAxisLocation','top');
    ylim(handles.DSpectrumMask,[min(VHalf)-.1*abs(max(VHalf)-min(VHalf)) max(VHalf)+.1*abs(max(VHalf)-min(VHalf))]);
    xlim(handles.DSpectrumMask,[RawFreq(get(handles.DZoomAS,'Value')),RawFreq(get(handles.DZoomBS,'Value'))]);
    xlim(handles.DSpectrumMaskC,[get(handles.DZoomAS,'Value') get(handles.DZoomBS,'Value')]);

    refresh(FILTERGUI);
    
    if handles.metricdata.DMFLAG == 0
        % Filter: FIX MODE
    elseif handles.metricdata.DMFLAG == 1
        % Filter: Mask MODE
        FilFFT = RawFFT .* MASKF;
        FiliFFT = ifft(FilFFT);
        FilDyn = real(FiliFFT);
    end

    plot(handles.FilDynAxes,FilDyn);
    axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

    handles.metricdata.FilDyn = FilDyn;

    set(handles.CLTru,'Value',0);
    set(handles.CLRaw,'Value',0);
    
    guidata(hObject, handles);

else
    msgbox('Mask Size Error');
    set(handles.DCommandE, 'String', '');
end

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function DCommandE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DCommandE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
% E. CK Forward Backward
% --------------------------------------------------------------------


% --- Executes on slider movement.
function ESpanS_Callback(hObject, eventdata, handles)
% hObject    handle to ESpanS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.ESpanE,'String',sprintf('%d', round(get(hObject,'Value'))));

ETableShow = get(handles.ETable,'data');
ETableRaw = flipud(sortrows([ETableShow; [-ETableShow(:,1) ETableShow(:,2:3)]],1));

Kfb = ETableRaw(:,1)';                
PI = ETableRaw(:,2)';
W = ETableRaw(:,3)';

refresh(FILTERGUI);
FilDyn = CKFILTER(handles.metricdata.RawDyn', round(get(hObject,'Value')), Kfb, W, PI);
FilDyn = FilDyn';


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function ESpanS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ESpanS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function ESpanE_Callback(hObject, eventdata, handles)
% hObject    handle to ESpanE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ESpanE as text
%        str2double(get(hObject,'String')) returns contents of ESpanE as a double

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

set(handles.ESpanS,'Value',str2num(get(hObject,'String')));

ETableShow = get(handles.ETable,'data');
ETableRaw = flipud(sortrows([ETableShow; [-ETableShow(:,1) ETableShow(:,2:3)]],1));

Kfb = ETableRaw(:,1)';                
PI = ETableRaw(:,2)';
W = ETableRaw(:,3)';


refresh(FILTERGUI);
FilDyn = CKFILTER(handles.metricdata.RawDyn', round(get(handles.ESpanS,'Value')), Kfb, W, PI);
FilDyn = FilDyn';


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function ESpanE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ESpanE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on slider movement.
function EBankS_Callback(hObject, eventdata, handles)
% hObject    handle to EBankS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

defaultBANK = round(get(hObject,'Value'));

set(handles.EBankE,'String',sprintf('%d', defaultBANK));

% Initail Table
BANK = 2.^(1:defaultBANK);
nbank = defaultBANK*2;

Kfb = sort([BANK -BANK],'descend'); %C1                
PI = ones(1,nbank)./nbank; %C2
defaultW = 100; W = ones(1,nbank).*defaultW; %C3

ETableRaw = [Kfb; PI; W]';
ETableShow = sortrows(ETableRaw(1:defaultBANK,:),1);

set(handles.ETable,'data',ETableShow);


refresh(FILTERGUI);
FilDyn = CKFILTER(handles.metricdata.RawDyn', round(get(handles.ESpanS,'Value')), Kfb, W, PI);
FilDyn = FilDyn';


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function EBankS_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EBankS (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function EBankE_Callback(hObject, eventdata, handles)
% hObject    handle to EBankE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of EBankE as text
%        str2double(get(hObject,'String')) returns contents of EBankE as a double

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

defaultBANK = str2num(get(hObject,'String'));

set(handles.ESpanS,'Value', defaultBANK);

% Initail Table
BANK = 2.^(1:defaultBANK);
nbank = defaultBANK*2;

Kfb = sort([BANK -BANK],'descend'); %C1                
PI = ones(1,nbank)./nbank; %C2
defaultW = 100; W = ones(1,nbank).*defaultW; %C3

ETableRaw = [Kfb; PI; W]';
ETableShow = sortrows(ETableRaw(1:defaultBANK,:),1);

set(handles.ETable,'data',ETableShow);


refresh(FILTERGUI);
FilDyn = CKFILTER(handles.metricdata.RawDyn', round(get(handles.ESpanS,'Value')), Kfb, W, PI);
FilDyn = FilDyn';


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --- Executes during object creation, after setting all properties.
function EBankE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EBankE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in EPIC.
function EPIC_Callback(hObject, eventdata, handles)
% hObject    handle to EPIC (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of EPIC

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

if get(hObject,'Value')
    set(handles.ETable,'ColumnEditable', logical([1 0 1]));
else
    set(handles.ETable,'ColumnEditable', logical([1 1 1]));
end

enableButtons(handles);


% --- Executes on button press in EPIC.
function EWC_Callback(hObject, eventdata, handles)
% hObject    handle to EWC (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of EWC

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

if get(hObject,'Value')
    ETableRaw = get(handles.ETable, 'data');
    ETableRaw(:,3) = mean(ETableRaw(:,3));
    set(handles.ETable, 'data', ETableRaw);
end

enableButtons(handles);


% --- Executes when entered data in editable cell(s) in ETable.
function ETable_CellEditCallback(hObject, eventdata, handles)
% hObject    handle to ETable (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) edited
%	PreviousData: previous data for the cell(s) edited
%	EditData: string(s) entered by the user
%	NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
%	Error: error string when failed to convert EditData to appropriate value for Data
% handles    structure with handles and user data (see GUIDATA)

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

ETableIndices = eventdata.Indices;
ETableColumnIndex = ETableIndices(2);

if ETableColumnIndex == 1
    %reorder
    ETableRaw = get(handles.ETable, 'data');
    ETableShow = sortrows(ETableRaw, 1);
    set(handles.ETable, 'data', ETableShow);
elseif ETableColumnIndex == 3
    if get(handles.EWC,'Value')
        %update whole W
        ETableRaw = get(handles.ETable, 'data');
        ETableRaw(:,3) = str2double(eventdata.EditData);
        set(handles.ETable, 'data', ETableRaw);
    end 
end

enableButtons(handles);


% --- Executes on button press in ETDONE.
function ETDONE_Callback(hObject, eventdata, handles)
% hObject    handle to ETDONE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

ETableShow = get(handles.ETable,'data');

% normalize priori probabilities
ETableShow(:,2) = ETableShow(:,2).*(.5/sum(ETableShow(:,2)));
set(handles.ETable, 'data', ETableShow);

ETableRaw = flipud(sortrows([ETableShow; [-ETableShow(:,1) ETableShow(:,2:3)]],1));

Kfb = ETableRaw(:,1)';                
PI = ETableRaw(:,2)';
W = ETableRaw(:,3)';


refresh(FILTERGUI);
FilDyn = CKFILTER(handles.metricdata.RawDyn', round(get(hObject,'Value')), Kfb, W, PI);
FilDyn = FilDyn';


plot(handles.FilDynAxes,FilDyn);
axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);

handles.metricdata.FilDyn = FilDyn;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);
guidata(hObject, handles);

enableButtons(handles);


% --------------------------------------------------------------------
% LINKING
% --------------------------------------------------------------------


% --- Executes on button press in CLTru.
function CLTru_Callback(hObject, eventdata, handles)
% hObject    handle to CLTru (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of CLTru

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

if handles.metricdata.TFLAG && handles.metricdata.FFLAG
    
    TruDyn = handles.metricdata.TruDyn;
    RawDyn = handles.metricdata.RawDyn;
    FilDyn = handles.metricdata.FilDyn;

    cla(handles.FilDynAxes);
    set(handles.FilDynAxes,'NextPlot','add');
    
    if get(hObject,'Value')
        if get(handles.CLRaw,'Value')
            plot(handles.FilDynAxes,RawDyn,'Color',[.4 .4 .4],'Marker','.','LineStyle','none');
            plot(handles.FilDynAxes,FilDyn,'b-');
            plot(handles.FilDynAxes,TruDyn,'r-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min([TruDyn; RawDyn; FilDyn])-.1*abs(max([TruDyn; RawDyn; FilDyn])-min([TruDyn; RawDyn; FilDyn])) max([TruDyn; RawDyn; FilDyn])+.1*abs(max([TruDyn; RawDyn; FilDyn])-min([TruDyn; RawDyn; FilDyn]))]);
        else
            plot(handles.FilDynAxes,FilDyn,'b-');
            plot(handles.FilDynAxes,TruDyn,'r-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min([TruDyn; FilDyn])-.1*abs(max([TruDyn; FilDyn])-min([TruDyn; FilDyn])) max([TruDyn; FilDyn])+.1*abs(max([TruDyn; FilDyn])-min([TruDyn; FilDyn]))]);
        end
    else
        if get(handles.CLRaw,'Value')
            plot(handles.FilDynAxes,RawDyn,'Color',[.4 .4 .4],'Marker','.','LineStyle','none');
            plot(handles.FilDynAxes,FilDyn,'b-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min([RawDyn; FilDyn])-.1*abs(max([RawDyn; FilDyn])-min([RawDyn; FilDyn])) max([RawDyn; FilDyn])+.1*abs(max([RawDyn; FilDyn])-min([RawDyn; FilDyn]))]);
        else
            plot(handles.FilDynAxes,FilDyn,'b-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);
        end
    end
    set(handles.FilDynAxes,'NextPlot','replace');
    
else
    set(hObject,'Value',0);
end

enableButtons(handles);


% --- Executes on button press in CLRaw.
function CLRaw_Callback(hObject, eventdata, handles)
% hObject    handle to CLRaw (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of CLRaw

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

if handles.metricdata.RFLAG && handles.metricdata.FFLAG
    
    TruDyn = handles.metricdata.TruDyn;
    RawDyn = handles.metricdata.RawDyn;
    FilDyn = handles.metricdata.FilDyn;

    cla(handles.FilDynAxes);
    set(handles.FilDynAxes,'NextPlot','add');
    
    if get(hObject,'Value')
        if get(handles.CLTru,'Value')
            plot(handles.FilDynAxes,RawDyn,'Color',[.4 .4 .4],'Marker','.','LineStyle','none');
            plot(handles.FilDynAxes,FilDyn,'b-');
            plot(handles.FilDynAxes,TruDyn,'r-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min([TruDyn; RawDyn; FilDyn])-.1*abs(max([TruDyn; RawDyn; FilDyn])-min([TruDyn; RawDyn; FilDyn])) max([TruDyn; RawDyn; FilDyn])+.1*abs(max([TruDyn; RawDyn; FilDyn])-min([TruDyn; RawDyn; FilDyn]))]);
        else
            plot(handles.FilDynAxes,RawDyn,'Color',[.4 .4 .4],'Marker','.','LineStyle','none');
            plot(handles.FilDynAxes,FilDyn,'b-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min([RawDyn; FilDyn])-.1*abs(max([RawDyn; FilDyn])-min([RawDyn; FilDyn])) max([RawDyn; FilDyn])+.1*abs(max([RawDyn; FilDyn])-min([RawDyn; FilDyn]))]);
        end
    else
        if get(handles.CLTru,'Value')
            plot(handles.FilDynAxes,FilDyn,'b-');
            plot(handles.FilDynAxes,TruDyn,'r-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min([TruDyn; FilDyn])-.1*abs(max([TruDyn; FilDyn])-min([TruDyn; FilDyn])) max([TruDyn; FilDyn])+.1*abs(max([TruDyn; FilDyn])-min([TruDyn; FilDyn]))]);
        else
            plot(handles.FilDynAxes,FilDyn,'b-');
            axis(handles.FilDynAxes,[1 length(FilDyn) min(FilDyn)-.1*abs(max(FilDyn)-min(FilDyn)) max(FilDyn)+.1*abs(max(FilDyn)-min(FilDyn))]);
        end
    end
    set(handles.FilDynAxes,'NextPlot','replace');
    
else
    set(hObject,'Value',0);
end

enableButtons(handles);


% --------------------------------------------------------------------
% RELOAD Example
% --------------------------------------------------------------------


% --- Executes on button press in Example.
function Example_Callback(hObject, eventdata, handles)
% hObject    handle to Example (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

disableButtons(handles);
refresh(FILTERGUI); %redraws the GUI to reflect changes

% Off Parameters
set(handles.PanelA,'Visible','off');
set(handles.PanelC,'Visible','off');
set(handles.PanelD,'Visible','off');
set(handles.PanelE,'Visible','off');

% Random seed
rand('twister', sum(100*clock));

example = 2;

switch example
    case 1
        % Load Example: Random Markov Chain Simulation with normal noise
        % Transition Matrix
        egP = [0.92 0.08; 0.13 0.87];
        % Generate Markov Chain with Stages 0 or 1
        egTruStage = (Markov_Chain(egP,1,200)-1)';
        % Alter time interval
        egTruDyn = kron(egTruStage,ones(50,1));
        % Adding Gaussion Noise
        sigma=1;
        egRawDyn = egTruDyn + (sigma^2).*randn(10000,1);
        % Filter: Moving Average Filter
        span = 100;
        egFilDyn = smooth(egRawDyn, span,'moving');

        set(handles.TD, 'String', ['Ture Dynamics: ' 'Example. Markov Chain Simulation']);
        set(handles.RD, 'String', ['Raw Dynamics: ' 'Example. Gaussion Noise (Sigma = 1)']);
        set(handles.FD, 'String', ['Filter Dynamics: ' 'Example. Moving Average']);
        set(handles.FilMethod,'Value',2);
    case 2
        % Load Example: FFT iFFT Sin Signal with normal noise
        % Initialization
        dt = 1/1000;                                                   % Smapling Rate
        et = 10;                                                       % End of Interval
        t = (0:dt:(et-dt))';                                           % Sampling Range
        egTruDyn = 3*sin(4*2*pi*t) + 5*sin(2*2*pi*t);                  % Signal Model
        sigma=1;
        egRawDyn = egTruDyn + (sigma^2).*randn(10000,1);               % Signal with Noise
        % Fourier Transform
        egRawFFT = fft(egRawDyn);                                      % Fourier Transform
        n = size(egRawDyn,1)/2;                                        % Scaling Size
        egRawFreq = (0:9999)/(2*n*dt);                                 % Freqency
        egRawAmpS = egRawFFT/n;                                        % Amplitude Spectrum
        egRFMax = max(abs(egRawFFT));
        % Filter: FIX MODE
        radius = 0.2;
        egFilFFT = egRawFFT;
        egFilFFT(abs(egRawAmpS)<(egRFMax/n*radius)) = 0;               % Set to Zeros within Radius
        egFiliFFT = ifft(egFilFFT);                                    % inverse Fourier Transform
        egFilDyn = real(egFiliFFT);                                    % Remove Imaginary Parts

        set(handles.TD, 'String', ['Ture Dynamics: ' 'Example. FFT iFFT Sin Signal']);
        set(handles.RD, 'String', ['Raw Dynamics: ' 'Example. Gaussion Noise (Sigma = 1)']);
        set(handles.FD, 'String', ['Filter Dynamics: ' 'Example. FIX MODE (Radius = 0.2)']);
        set(handles.FilMethod,'Value',5);
end


plot(handles.TruDynAxes,egTruDyn);
axis(handles.TruDynAxes,[1 length(egTruDyn) min(egTruDyn)-.1*abs(max(egTruDyn)-min(egTruDyn)) max(egTruDyn)+.1*abs(max(egTruDyn)-min(egTruDyn))]);

plot(handles.RawDynAxes,egRawDyn);
axis(handles.RawDynAxes,[1 length(egRawDyn) min(egRawDyn)-.1*abs(max(egRawDyn)-min(egRawDyn)) max(egRawDyn)+.1*abs(max(egRawDyn)-min(egRawDyn))]);

plot(handles.FilDynAxes,egFilDyn);
axis(handles.FilDynAxes,[1 length(egFilDyn) min(egFilDyn)-.1*abs(max(egFilDyn)-min(egFilDyn)) max(egFilDyn)+.1*abs(max(egFilDyn)-min(egFilDyn))]);

            
handles.metricdata.TruDyn = egTruDyn;
handles.metricdata.RawDyn = egRawDyn;
handles.metricdata.FilDyn = egFilDyn;

handles.metricdata.TFLAG = 1;
handles.metricdata.RFLAG = 1;
handles.metricdata.FFLAG = 1;

set(handles.CLTru,'Value',0);
set(handles.CLRaw,'Value',0);

guidata(hObject, handles);

enableButtons(handles);


% --------------------------------------------------------------------
% DISABLE AND ENABLE
% --------------------------------------------------------------------


function disableButtons(handles)
%change the mouse cursor to an hourglass
set(handles.figure1,'Pointer','watch');
 
%disable all the buttons so they cannot be pressed
set(handles.LoadRawDyn,'Enable','off');
set(handles.LoadTruDyn,'Enable','off');
set(handles.CLRaw,'Enable','off');
set(handles.CLTru,'Enable','off');

set(handles.Example,'Enable','off');
set(handles.Save,'Enable','off');

set(handles.FilMethod,'Enable','off');

%PanelA
set(handles.ASpanS,'Enable','off');
set(handles.ASpanE,'Enable','off');

%PanelB
set(handles.BDone,'Enable','off');
set(handles.BStateNumS,'Enable','off');
set(handles.BStateNumE,'Enable','off');
set(handles.BTMatrixT,'Enable','off');
set(handles.BEParaT,'Enable','off');
set(handles.BTMatrixFixT,'Enable','off');
set(handles.BEParaFixT,'Enable','off');

%PanelC
set(handles.CProcessS,'Enable','off');
set(handles.CProcessE,'Enable','off');
set(handles.CMeasureS,'Enable','off');
set(handles.CMeasureE,'Enable','off');

%PanelD
set(handles.DZoomAS,'Enable','off');
set(handles.DZoomAE,'Enable','off');
set(handles.DZoomBS,'Enable','off');
set(handles.DZoomBE,'Enable','off');
set(handles.DRadiusS,'Enable','off');
set(handles.DRadiusE,'Enable','off');
set(handles.DSquare,'Enable','off');
set(handles.DMSwitch,'Enable','off');
set(handles.DFSwitch,'Enable','off');
set(handles.DCommandE,'Enable','off');

%PanelE
set(handles.ESpanS,'Enable','off');
set(handles.ESpanE,'Enable','off');
set(handles.EBankS,'Enable','off');
set(handles.EBankE,'Enable','off');
set(handles.EPIC,'Enable','off');
set(handles.EWC,'Enable','off');
set(handles.ETDONE,'Enable','off');
set(handles.ETable,'Enable','off');
 

function enableButtons(handles)
%change the mouse cursor to an arrow
set(handles.figure1,'Pointer','arrow');
 
%enable all the buttons so they can be pressed
set(handles.LoadRawDyn,'Enable','on');
set(handles.LoadTruDyn,'Enable','on');
set(handles.CLRaw,'Enable','on');
set(handles.CLTru,'Enable','on');

set(handles.Example,'Enable','on');
set(handles.Save,'Enable','on');

set(handles.FilMethod,'Enable','on');

%PanelA
set(handles.ASpanS,'Enable','on');
set(handles.ASpanE,'Enable','on');

%PanelB
set(handles.BDone,'Enable','on');
set(handles.BStateNumS,'Enable','on');
set(handles.BStateNumE,'Enable','on');
set(handles.BTMatrixT,'Enable','on');
set(handles.BEParaT,'Enable','on');
set(handles.BTMatrixFixT,'Enable','on');
set(handles.BEParaFixT,'Enable','on');

%PanelC
set(handles.CProcessS,'Enable','on');
set(handles.CProcessE,'Enable','on');
set(handles.CMeasureS,'Enable','on');
set(handles.CMeasureE,'Enable','on');

%PanelD
set(handles.DZoomAS,'Enable','on');
set(handles.DZoomAE,'Enable','on');
set(handles.DZoomBS,'Enable','on');
set(handles.DZoomBE,'Enable','on');
set(handles.DRadiusS,'Enable','on');
set(handles.DRadiusE,'Enable','on');
set(handles.DSquare,'Enable','on');
set(handles.DMSwitch,'Enable','on');
set(handles.DFSwitch,'Enable','on');
set(handles.DCommandE,'Enable','on');

%PanelE
set(handles.ESpanS,'Enable','on');
set(handles.ESpanE,'Enable','on');
set(handles.EBankS,'Enable','on');
set(handles.EBankE,'Enable','on');
set(handles.EPIC,'Enable','on');
set(handles.EWC,'Enable','on');
set(handles.ETDONE,'Enable','on');
set(handles.ETable,'Enable','on');
